<!--货品信息-->
<template>
    <el-form :model="procform" ref="procref" :inline="true" style="text-align: left;">
        <el-form-item label="货品名称:" prop="name">
            <el-input placeholder="请输入货品名称" v-model="procform.name"></el-input>
        </el-form-item>
        <el-form-item label="仓库" prop="whid">
            <el-select placeholder="请选择" v-model="procform.whid" style="width:200px">
                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="货品分类" prop="type">
            <el-tree-select v-model="procform.type" :data="types"
                    :props="{
                        value: 'type_id',
                        label: 'type_name',
                        children: 'children'
                    }"
                    placeholder="请选择"
                    style="width: 200px"
                    check-strictly
                    default-expand-all/>
        </el-form-item>
        <el-form-item prop="inventory">
            <el-checkbox v-model="procform.inventory" label="显示有库存货品"></el-checkbox>
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
            <el-button @click="AdvancedSearch">高级查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="ShowAdd">添加</el-button>
        <el-button type="danger" @click="DeleteAll">删除</el-button>
        <el-button @click="Import">导入</el-button>
        <el-button @click="Export">导出</el-button>
        <el-button @click="Refresh">刷新</el-button>
    </div>
    <!--表格-->
    <el-table :data="procdata" stripe style="margin-top: 10px;"  @selection-change="SelectChange">
        <el-table-column fixed  type="selection"></el-table-column>
        <el-table-column fixed  type="index" label="序号" width="70px"></el-table-column>
        <el-table-column fixed  label="货品编号" width="150px">
            <template #default="scope">
                <span style="color: green;cursor: pointer;" @click="ShowInfo(scope.row)">{{ scope.row.proc_code }}</span>
            </template>
        </el-table-column>
        <el-table-column fixed prop="proc_name" label="货品名称" width="150px"></el-table-column>
        <el-table-column fixed prop="proc_status" label="状态"></el-table-column>
        <el-table-column prop="type_name" label="货品类型"></el-table-column>
        <el-table-column prop="proc_model" label="规格型号"></el-table-column>
        <el-table-column prop="proc_primary_unit" label="单位"></el-table-column>
        <el-table-column prop="proc_primary_barcode" label="条码"></el-table-column>
        <el-table-column label="入库参考价/元" width="120px">
            <template #default="scope">
                <span>{{ (scope.row.instock_price || 0).toFixed(2) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="出库参考价/元" width="120px">
            <template #default="scope">
                <span>{{ (scope.row.outstock_price || 0).toFixed(2) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="显示顺序">
            <template #default="scope">
                <span>{{ scope.row.proc_sort || 0 }}</span>
            </template>
        </el-table-column>
        <el-table-column label="总库存">
            <template #default="scope">
                <span>{{ scope.row.proc_inventory || 0 }}</span>
            </template>
        </el-table-column>
        <el-table-column label="库存总金额" width="120px">
            <template #default="scope">
                <span>{{ (scope.row.proc_inventory_money || 0).toFixed(2) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="is_datamanagement" label="保质期管理" width="120px"></el-table-column>
        <el-table-column label="保质期">
            <template #default="scope">
                <span>{{ scope.row.proc_expirationdate || 0 }}</span>
            </template>
        </el-table-column>
        <el-table-column label="预警天数">
            <template #default="scope">
                <span>{{ scope.row.proc_Warningdays || 0 }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="proc_primary_barcode" label="条码" width="150px"></el-table-column>
        <el-table-column prop="create_name" label="操作人"></el-table-column>
        <el-table-column prop="create_time" label="操作时间" width="200px"></el-table-column>
        <el-table-column label="操作" fixed="right" width="160px">
            <template #default="scope">
                <el-button type="success" text="编辑" @click="ShowUpdate(scope.row)">编辑</el-button>
                <el-button type="danger" text="删除" @click="ShowDelete(scope.row.proc_id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

     <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>

     <!--删除模态框-->
    <el-dialog v-model="DeleteialogVisible" width="400" style="text-align: left;"  align-center>
        <span>确定删除吗?</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="DeleteialogVisible = false">取消</el-button>
                <el-button type="primary" @click="Delete()">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!--高级查询-->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">高级查询</h4>
        </template>
        <template #default>
            <el-form label-width="120px" label-position="top" :model="searchform" ref="searchref">
                <el-row :gutter="24">
                    <!-- 左列 -->
                    <el-col :span="12">
                        <el-form-item label="货品编号"  prop="code">
                            <el-input placeholder="请输入" v-model="searchform.code"/>
                        </el-form-item>
                        <el-form-item label="货品类型" prop="typeid">
                            <el-tree-select v-model="searchform.typeid" :data="types"
                                :props="{
                                    value: 'type_id',
                                    label: 'type_name',
                                    children: 'children'
                                }"
                                placeholder="请选择"
                                check-strictly
                                default-expand-all/>
                        </el-form-item>
                        <el-form-item label="单位" prop="unit">
                            <el-select placeholder="请选择" v-model="searchform.unit"></el-select>
                        </el-form-item>
                        <el-form-item label="出库参考价/元" prop="outprice">
                            <div style="display: flex; align-items: center; ">
                                <el-input placeholder="请输入"  v-model="searchform.startoutprice"/>
                                <span style="margin: 0 8px;">~</span>
                                <el-input placeholder="请输入"  v-model="searchform.endoutprice"/>
                            </div>
                        </el-form-item>
                        <el-form-item label="状态" prop="status">
                            <el-select placeholder="请选择" v-model="searchform.status">
                                <el-option label="启用" value="1" />
                                <el-option label="禁用" value="0" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="仓库" prop="whid">
                            <el-select placeholder="请选择" v-model="searchform.whid">
                                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="操作时间:" prop="timeRange">
                            <el-date-picker v-model="searchform.timeRange" :value-format="dateFormat" type="datetimerange"
                                range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
                        </el-form-item>
                    </el-col>
                    <!-- 右列 -->
                    <el-col :span="12">
                        <el-form-item label="货品名称" prop="name">
                            <el-input placeholder="请输入" v-model="searchform.name" />
                        </el-form-item>
                        <el-form-item label="规格型号" prop="model">
                            <el-input placeholder="请输入" v-model="searchform.model" />
                        </el-form-item>
                        <el-form-item label="入库参考价/元" prop="inprice">
                            <div style="display: flex; align-items: center;">
                                <el-input placeholder="请输入" v-model="searchform.startinprice" />
                                <span style="margin: 0 8px;">~</span>
                                <el-input placeholder="请输入" v-model="searchform.endinprice" />
                            </div>
                        </el-form-item>
                        <el-form-item label="保质期管理" prop="is_datamanagement">
                            <el-select placeholder="请选择" v-model="searchform.is_datamanagement">
                                <el-option label="开启" value="1" />
                                <el-option label="关闭" value="0" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="预警天数(天)"  prop="warningdays">
                            <div style="display: flex; align-items: center;">
                                <el-input placeholder="请输入" v-model="searchform.startwarningdays"/>
                                <span style="margin: 0 8px;">~</span>
                                <el-input placeholder="请输入" v-model="searchform.endwarningdays"/>
                            </div>
                        </el-form-item>
                        <el-form-item label="条码" prop="barcode">
                            <el-input placeholder="请输入" v-model="searchform.barcode"/>
                        </el-form-item>
                        <el-form-item label="操作人" prop="createname">
                            <el-input placeholder="请输入"  v-model="searchform.createname"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="AdvancedReset">重置</el-button>
                <el-button @click="drawer = false">关闭</el-button>
                <el-button type="primary" @click="AdvancedOk">确定</el-button>
            </div>
        </template>
    </el-drawer>
    
</template>

<script>
import {ref,reactive,onMounted } from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';//路由
import * as XLSX from 'xlsx';
export default {
setup()
    {
        const router = useRouter();//路由
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));
        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //查询所有仓库
        const warehouse=ref([]);
        function AllWarehouse(){
            http.get("/Warehouse/GetWarehouses")
            .then(res=>{
                warehouse.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有货品类型绑定到下拉框
        const types=ref([]);
        function AllType(){
            http.get("/ProductType/GetAllProductTypes")
            .then(res=>{
                types.value=convertToTree(res.data);
            }).catch(err=>{
                console.log(err);
            })
        }

         // 将扁平数据转换为树状结构的函数，同时保留所有相关节点及其父节点
         function convertToTree(data) {
            // 先创建一个以 type_id 为键的映射表，方便快速查找节点
            const map = {};
            data.forEach(item => {
                map[item.type_id] = { ...item, children: [] };
            });
            const tree = [];
            data.forEach(item => {
                const node = map[item.type_id];
                if (item.type_pid === 0) {
                    // 如果是顶层节点，直接添加到树中
                    tree.push(node);
                } else {
                    const parent = map[item.type_pid];
                    if (parent) {
                        // 如果父节点存在，将当前节点添加到父节点的 children 中
                        parent.children.push(node);
                    } else {
                        // 如果父节点不存在，将其作为顶层节点添加到树中
                        tree.push(node);
                    }
                }
            });
            return tree;
        }

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }
        //当前procid
        const procid=ref(0);

        //导出
        function Export(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                "货品编号": row.proc_code,
                "货品名称": row.proc_name,
                "货品类型": row.type_name,
                "规格型号": row.proc_model,
                "主单位": row.proc_primary_unit,
                "入库参考价": row.instock_price,
                "出库参考价": row.outstock_price,
                "总库存": row.proc_inventory,
                "库存总金额": row.proc_inventory_money,
                "状态": row.proc_status,
                "条码": row.proc_bar_code,
                "保质期管理": row.is_datamanagement,
                "保质期": row.proc_expirationdate,
                "预警天数": row.proc_Warningdays,
                "操作人": row.create_name,
                "操作时间": row.create_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet (excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "货品信息");
            // 导出并下载
            XLSX.writeFile(wb, `货品信息${new Date().toLocaleDateString()}.xlsx`);
        }

         //导入
         function Import() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.xlsx, .xls';
            input.onchange = (event) => {
                const file = event.target.files[0];
                if (file) {
                    const formData = new FormData();
                    formData.append('file', file);
                    //导入
                    http.post("/Product/ImportProduct", formData)
                    .then(res => {
                        const data=res.data;
                        console.log("草泥马")
                        console.log(data.successCount)
                        // 成功导入提示
                        if (data.successCount > 0) {
                            ElMessage.success(`成功导入数据`);
                        }
                        // 处理重复数据提示
                        if (data.duplicateCount > 0) {
                            // 创建更详细的重复数据提示
                            let duplicateMessage = `发现 ${data.duplicateCount} 条重复数据，未导入<br>`;
                            // 如果有具体重复行信息
                            if (data.errors && data.errors.length > 0) {
                                // 只筛选出重复相关的错误信息
                                const duplicateErrors = data.errors.filter(err => 
                                    err.includes("货品类型编号") || err.includes("货品类型名称"));
                                
                                // 添加到提示信息中
                                duplicateErrors.forEach(err => {
                                    duplicateMessage += `• ${err}<br>`;
                                });
                            }
                            // 使用更明显的提示方式
                            ElMessageBox.alert(duplicateMessage, '重复数据提示', {
                                confirmButtonText: '确定',
                                customClass: 'duplicate-message-box',
                                dangerouslyUseHTMLString: true
                            });
                            // 同时显示一个简短的警告提示
                            ElMessage.warning({
                                message: `发现 ${data.duplicateCount} 条重复数据`,
                            });
                        }
                        All(); // 刷新数据
                    })
                    .catch(err => {
                        console.error('导入错误:', err);
                    });
                }
            };
            input.click();
        }

        //#region 查询

        //表单数据
        const procref=ref("");
        const procform=reactive({
            name:"",
            type:"",
            inventory:false,
            whid:"",
        })
        //表格数据
        const procdata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);

        //重置
        function Reset(){
            procref.value?.resetFields();
            All();
        }

        //查询
        function Search() {
            All();
        }

        //查询数据
        function All(){
            http.get("/Product/GetProduct", {
                params: {
                    name: procform.name,
                    type: procform.type,
                    inventory:procform.inventory,
                    whid:procform.whid,
                    CurrentPage: currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    create_time: formatDateTime(new Date(item.create_time)),
                    proc_status: item.proc_status === 0 ? '启用' : '禁用',
                    is_datamanagement:item.is_datamanagement === 0 ? '关闭' : '开启'
                }));
                procdata.value = Data;
            }).catch(err => {
                console.log(err)
            })
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }

        //#endregion

        //#region 跳转添加页面
       
        function ShowAdd(){
            router.push("productadd");
        }

        //#endregion

        //#region 删除

            //删除模态框
            const DeleteialogVisible=ref(false);
            //删除模态框
            function ShowDelete(id){
                procid.value=id;
                DeleteialogVisible.value=true;
            }
            function Delete(){
                http.put("/Product/DeleteProduct?id="+procid.value)
                .then(res=>{
                    if(res.data>0){
                        ElMessage({
                            message: '删除成功.',
                            type: 'success',
                        })
                        All();
                        DeleteialogVisible.value=false;
                    }else{
                        ElMessage.error('删除失败.')
                    }
                }).catch(err=>{
                    console.log(err);
                })
            }
            //批量删除
            function DeleteAll(){
                if(selectdata.value.length==0){
                    ElMessage({
                        message: '请选择要删除的数据.',
                        type: 'warning',
                    })
                    return;
                }
                //循环删除
                selectdata.value.forEach(item => {
                    http.put("/Product/DeleteProduct?id="+item.proc_id)
                    .then(res=>{
                        if(res.data>0){
                            ElMessage({
                                message: '删除成功.',
                                type: 'success',
                            })
                            All();
                            DeleteialogVisible.value=false;
                        }else{
                            ElMessage.error('删除失败.')
                        }
                    }).catch(err=>{
                        console.log(err);
                    })
                });
            }


        //#endregion

        //#region 跳转修改页面

         function ShowUpdate(row){
            //传当前对应货品Id过去
            router.push({
                name:"productupdate",
                params:{
                    productid:row.proc_id,
                    productcode:row.proc_code
                }
            })
        }
        //#endregion

        //#region 跳转到货品详情界面
        
        function ShowInfo(row){
            router.push({
                name:"productInfo",
                params:{
                    productid:row.proc_id,
                    productcode:row.proc_code
                }
            })
        }

        //#endregion
        

        //#region 高级查询
        const drawer=ref(false);
        function AdvancedSearch(){
             drawer.value=true;
        }
        const searchref=ref("");
        const searchform=reactive({
            code:"",
            name:"",
            typeid:"",
            model:"",
            unit:"",
            inprice:"",
            startinprice:"",
            endinprice:"",
            outprice:"",
            startoutprice:"",
            endoutprice:"",
            is_datamanagement:"",
            warningdays:"",
            startwarningdays:"",
            endwarningdays:"",
            status:"",
            barcode:"",
            whid:"",
            createname:"",
            timeRange:[null,null]
        })

        //日期格式
        const dateFormat = 'YYYY-MM-DD HH:mm:ss';

        //重置
        function AdvancedReset(){
            searchref.value?.resetFields();
            searchform.startinprice="",
            searchform.endinprice="",
            searchform.startoutprice="",
            searchform.endoutprice="",
            searchform.startwarningdays="",
            searchform.endwarningdays=""
        }

        //高级查询
        function AdvancedOk(){
            http.get("/Product/GetAdvancedProduct",{
                params:{
                    code:searchform.code,
                    name:searchform.name,
                    typeid:searchform.typeid,
                    model:searchform.model,
                    unit:searchform.unit,
                    startinprice:searchform.startinprice,
                    endinprice:searchform.endinprice,
                    startoutprice:searchform.startoutprice,
                    endoutprice:searchform.endoutprice,
                    is_datamanagement:searchform.is_datamanagement,
                    startwarningdays:searchform.startwarningdays,
                    endwarningdays:searchform.endwarningdays,
                    status:searchform.status,
                    barcode:searchform.barcode,
                    whid:searchform.whid,
                    starttime:searchform.timeRange[0],
                    endtime:searchform.timeRange[1],
                    createname:searchform.createname,
                    CurrentPage:currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    create_time: formatDateTime(new Date(item.create_time)),
                    proc_status: item.type_status === 0 ? '启用' : '禁用',
                    is_datamanagement:item.is_datamanagement === 0 ? '关闭' : '开启'
                }));
                procdata.value = Data;
            }).catch(err => {
                console.log(err)
            })
        }

        //#endregion


        //刷新
        function Refresh(){
            All();
        }



        //挂载
        onMounted(() => {
            All();
            AllType();
            AllWarehouse();
        });

        return{
            user,
            formatDateTime,
            procdata,
            procform,
            procref,
            Reset,
            Search,
            All,
            handlePageChange,
            rows,
            currentPage,
            types,
            AllType,
            ShowAdd,
            selectdata,
            SelectChange,
            DeleteialogVisible,
            ShowDelete,
            Delete,
            DeleteAll,
            procid,
            Export,
            Import,
            ShowUpdate,
            ShowInfo,
            warehouse,
            drawer,
            AdvancedSearch,
            searchref,
            searchform,
            AdvancedReset,
            dateFormat,
            AdvancedOk,
            Refresh
        }
    }
}
</script>

<style scoped>

</style>